package ca.paulshin.yunatube.main;

import static ca.paulshin.yunatube.database.YuNaTubeSqliteDatabase.getInstance;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import ca.paulshin.yunatube.R;
import ca.paulshin.yunatube.YunaTubeApplication;
import ca.paulshin.yunatube.YunaTubeBaseFragment;
import ca.paulshin.yunatube.common.Constants;
import ca.paulshin.yunatube.common.Persistent;
import ca.paulshin.yunatube.common.Preference;
import ca.paulshin.yunatube.common.Utils;
import ca.paulshin.yunatube.database.Schema.TableNew;
import ca.paulshin.yunatube.services.DownloadService;
import ca.paulshin.yunatube.services.broadcast.DownloadReceiver.OnDownloadListener;
import ca.paulshin.yunatube.youtube.YouTubeActivity;

import com.squareup.picasso.Picasso;

public class MainContentFragment extends YunaTubeBaseFragment implements OnDownloadListener, OnClickListener/*, OnItemClickListener*/ {
	private static final int NUM_OF_NEW_CLIPS = 10;
	private static final int CARD_ALPHA = 150;
	private static final String IS_GUIDE_SHOWN = "is_guide_shown";

	public static final String XML_VERSION = "xml_version";
	
	private static List<String> newClipTitles = new ArrayList<String>(NUM_OF_NEW_CLIPS);
	private static List<String> newClipUrls = new ArrayList<String>(NUM_OF_NEW_CLIPS);
	
	private ImageView todayPhoto, slide;
	private String photoUrl;
	
	private Picasso picasso;
	
	private static final int GUIDE_DISAPPEAR = 10001;
	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == GUIDE_DISAPPEAR) {
				Animation animationFadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out);
				slide.startAnimation(animationFadeOut);
				slide.setVisibility(View.GONE);
				Preference.put(IS_GUIDE_SHOWN, true);
			}
			super.handleMessage(msg);
		}
	};
	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.main_content_fragment, null);
		
		ImageView hotNews = (ImageView) view.findViewById(R.id.hot_news);
		ImageView fact = (ImageView) view.findViewById(R.id.fact_image);
		todayPhoto = (ImageView)view.findViewById(R.id.today_photo);
		todayPhoto.setOnClickListener(this);
		
		hotNews.setOnClickListener(this);
		fact.setOnClickListener(this);
		
		picasso = Picasso.with(getActivity());

		// Show the slider guide
		slide = (ImageView) view.findViewById(R.id.slide_guide);
		if (!Preference.contains(IS_GUIDE_SHOWN) || !Preference.get(IS_GUIDE_SHOWN, true)) {
			handler.sendEmptyMessageDelayed(GUIDE_DISAPPEAR, 1500);
		} else {
			slide.setVisibility(View.GONE);
		}

		displayTimer(view);

		return view;
	}

	private void displayTimer(View view) {
		Date today = new Date();
		final Calendar todayCal = Calendar.getInstance();
		todayCal.setTime(today);

		final Calendar dDayCal = Calendar.getInstance();
		dDayCal.set(2014, 1, 20);

		long remaining = dDayCal.getTimeInMillis() - todayCal.getTimeInMillis();

		TextView countDown = (TextView) view.findViewById(R.id.olympics_countdown);
		countDown.setText(getString(R.string.dday_sochi, Utils.convertMillis(remaining)));
	}

	@Override
	public void onResume() {
		super.onResume();
		
		Utils.debug("Displaying existing results");
		displayData();
		
		if (!Utils.isNetworkAvailable()) {
			Utils.showToast(getActivity(), R.string.message_network_unavailable);
		}
	}

	private void displayNotices() {
		List<String> noticeList = Persistent.get(DownloadService.NOTICE_KEY, null);
		if (noticeList != null && noticeList.size() > 0) {
			LinearLayout notices = (LinearLayout) getView().findViewById(R.id.notice_layout);
			Drawable background = notices.getBackground();
			background.setAlpha(CARD_ALPHA);
			
			notices.removeAllViews();
			TextView tv;
			
			for (String notice : noticeList) {
				tv = new TextView(getActivity());
				LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams((int) LayoutParams.MATCH_PARENT, (int) LayoutParams.WRAP_CONTENT);
				tv.setPadding(5, 5, 5, 5);
				tv.setLayoutParams(textParams);
				tv.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small);
				
				if (notice.endsWith("*")) {
					tv.setText(notice.substring(0, notice.length() - 1));
					tv.setTypeface(null, Typeface.BOLD);
				}
				else
					tv.setText(notice);
				notices.addView(tv);
			}
		}
	}

	private void displayFact() {
		String factText = Persistent.getString(null, DownloadService.FACT_KEY);
		photoUrl = Persistent.getString(null, DownloadService.TODAY_PHOTO_KEY);
		if (!TextUtils.isEmpty(factText)) {
			LinearLayout factLayout = (LinearLayout) getView().findViewById(R.id.fact_layout);
			
			TextView tv = (TextView)factLayout.findViewById(R.id.fact_text);
			tv.setText(factText);
			
			LinearLayout factPhoto = (LinearLayout) factLayout.findViewById(R.id.fact_photo);
			Drawable background = factPhoto.getBackground();
			background.setAlpha(CARD_ALPHA);
			
			factLayout.setVisibility(View.VISIBLE);

			if (!TextUtils.isEmpty(photoUrl))
				picasso.load(photoUrl).placeholder(R.drawable.stub).centerCrop().resize(300, 300).into(todayPhoto);
			else
				todayPhoto.setVisibility(View.GONE);
		}
	}

	/*
	private void displayNewClipsUsingListView() {
		cursor = getInstance().fetchNewClips(NUM_OF_NEW_CLIPS);
		if (cursor.getCount() > 0) {
			NewClipAdapter adapter = new NewClipAdapter(getActivity(), cursor, 0);
			
			ListView newClipList = (ListView) getView().findViewById(R.id.new_clips_list);
			newClipList.setDividerHeight(0);
			
			// Set new height
			LayoutParams listParams = (LayoutParams) newClipList.getLayoutParams();
			int rowHeight = (int)YunaTubeApplication.densityDpi * 55;
			
			
			listParams.height = rowHeight * adapter.getCount();
			newClipList.setLayoutParams(listParams);
			newClipList.setAdapter(adapter);
			newClipList.setOnItemClickListener(this);
			newClipList.setVisibility(View.VISIBLE);
			getView().findViewById(R.id.new_clips_progress).setVisibility(View.GONE);
			
			// Hacky way to scroll the page to the top
			handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					ScrollView sun = (ScrollView)getView().findViewById(R.id.main_scroll);
					sun.fullScroll(ScrollView.FOCUS_UP);
				}
			};
			handler.sendEmptyMessageDelayed(0, 10);
		}
	}
	*/
	
	private void displayNewClips() {
		LinearLayout newClipsLayout = (LinearLayout) getView().findViewById(R.id.new_clips_layout);
		newClipsLayout.removeAllViews();
		newClipTitles.clear();
		newClipUrls.clear();

		// Get all of the rows from the database and create the item list
		Cursor cursor = getInstance().fetchNewClips(NUM_OF_NEW_CLIPS);
		String title, url;
		
		final float scale = getResources().getDisplayMetrics().density;
		int width = (int) (80 * scale + 0.5f);
		int height = (int) (50 * scale + 0.5f);
		
		LinearLayout.LayoutParams youtubeLayoutParams = new LinearLayout.LayoutParams((int) LayoutParams.MATCH_PARENT, (int) LayoutParams.WRAP_CONTENT);
		youtubeLayoutParams.setMargins(0, 6, 0, 6);
		LinearLayout.LayoutParams thumbNailLayoutParams = new LinearLayout.LayoutParams(width, height);
		thumbNailLayoutParams.setMargins(0, 6, 0, 6);
		LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams((int) LayoutParams.MATCH_PARENT, (int) LayoutParams.WRAP_CONTENT);
		
		LinearLayout youtubeLayout;
		ImageView thumbnail;
		TextView text;

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			title = cursor.getString(cursor.getColumnIndexOrThrow(TableNew.title));
			url = cursor.getString(cursor.getColumnIndexOrThrow(TableNew.url));
			newClipTitles.add(title);
			newClipUrls.add(url);

			youtubeLayout = new LinearLayout(getActivity());
			youtubeLayout.setLayoutParams(youtubeLayoutParams);
			youtubeLayout.setGravity(Gravity.CENTER_VERTICAL);
			youtubeLayout.setBackgroundResource(R.drawable.card_background_selector);
			Drawable background = youtubeLayout.getBackground();
			background.setAlpha(CARD_ALPHA);

			thumbnail = new ImageView(getActivity());
			thumbnail.setLayoutParams(thumbNailLayoutParams);
			thumbnail.setPadding(5, 5, 5, 5);
			picasso.load("http://i.ytimg.com/vi/" + url + "/2.jpg").placeholder(R.drawable.stub).centerCrop().resize(160, 100).into(thumbnail);
			youtubeLayout.addView(thumbnail);

			text = new TextView(getActivity());
			textParams.setMargins(6, 0, 0, 0);
			text.setLayoutParams(textParams);
			text.setTextAppearance(getActivity(), android.R.style.TextAppearance_Small);
			text.setText(title);
			youtubeLayout.addView(text);

			final String title_ = title;
			final String url_ = url;
			newClipsLayout.addView(youtubeLayout);

			youtubeLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Bundle bundle = new Bundle();
					bundle.putStringArray(YouTubeActivity.EXTRA_YOUTUBE_CLIPSET, new String[] { null, title_, url_ });
					Intent intent = new Intent(getActivity(), YouTubeActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
					getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
				}
			});
		}

		if (cursor != null)
			cursor.close();
	}

	@Override
	public void onDownload(Bundle bundle) {
		if (YunaTubeApplication.debuggable)
			Utils.showToast(getActivity(), "Loaded new ver: " + bundle.getInt(DownloadService.EXTRA_LATEST_XML_VERSION));

		if (getView() != null) {
			Utils.debug("Displaying newly loaded results");
			displayData();
		}
	}
	
	private void displayData() {
		displayNotices();

		if (Utils.isAppLocaleKorean())
			displayFact();

		displayNewClips();
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.hot_news:
			intent = new Intent(getActivity(), HotNewsActivity.class);
			break;
			
		case R.id.fact_image:
			Uri uri = Uri.parse(Constants.YUNAFACT);
			startActivity(new Intent(Intent.ACTION_VIEW, uri));
			break;
			
		case R.id.today_photo:
			if (TextUtils.isEmpty(photoUrl)) return;
			intent = new Intent(getActivity(), TodayPhotoActivity.class);
			intent.putExtra(TodayPhotoActivity.EXTRA_TODAY_PHOTO_URL, photoUrl);
			break;
		}
		startActivity(intent);
	}

/*
	@Override
	public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
		cursor.moveToPosition(position);
		String title = cursor.getString(cursor.getColumnIndexOrThrow(TableNew.title));
		String url = cursor.getString(cursor.getColumnIndexOrThrow(TableNew.url));
		
		Bundle bundle = new Bundle();
        bundle.putStringArray(YouTubeActivity.EXTRA_YOUTUBE_CLIPSET, new String[] { null, title, url });
        Intent intent = new Intent(getActivity(), YouTubeActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
	}
*/
	
	@Override
	public int getTitle() {
		return 0;
	}
	
	@Override
	public String getTextTitle() {
		return "";
	}

	@Override
	protected boolean getNetworkCheck() {
		return true;
	}

	@Override
	protected String getTrackerId() {
		return "main - content";
	}
}